#include<stdio.h>
#include<stdlib.h>

#include "def.h"
#include "nrio.h"
#include "nrarith.h"
#include "nralloc.h"
#include <math.h>


byte filter_moyenne(byte **m, int i, int j){
	return (m[i-1][j-1] +
			+ m[i-1][j]
			+ m[i-1][j+1]
			+ m[i][j-1]
			+ m[i][j]
			+ m[i][j+1]
			+ m[i+1][j-1]
			+ m[i+1][j]
			+ m[i+1][j+1])/9;
	
}



byte filter_sobel(byte **m, int i, int j){
//Sobel
//-1 0 1
//-2 0 2
//-1 0 1
	return abs((m[i-1][j-1]   *-1 +
			+ m[i-1][j] *-2
			+ m[i-1][j+1] *-1
			
			//+ m[i][j-1]   *0
			//+ m[i][j]   *0
			//+ m[i][j+1]   *0
			
			+ m[i+1][j-1] *1
			+ m[i+1][j]   *2
			+ m[i+1][j+1] *1
			)*1.0/4);
}

byte filter_sobelVertical(byte **m, int i, int j){
//Sobel
//-1 0 1
//-2 0 2
//-1 0 1


	return abs((m[i-1][j-1]   *-1 +
			//+ m[i-1][j] *0
			+ m[i-1][j+1] *1
			
			+ m[i][j-1]   *-2
			//+ m[i][j]   *0
			+ m[i][j+1]   *2
			
			+ m[i+1][j-1] *-1
			//+ m[i+1][j] *0
			+ m[i+1][j+1] *1
			)*1.0/4);
}


int main(void){
	long nrh,nrl,nch,ncl;
	byte **I;
	byte **I_temp;
	int i,j;
	char filename[100] = "cubesx3_Sobel_norme_gradient_avec_seuillage";
	
		
	I=LoadPGM_bmatrix("cubesx3.pgm",&nrl,&nrh,&ncl,&nch);
	
	
	//seuillage binaire, transformation en image strictement noir et blanc
	for(i=nrl;i<nrh;i++){
		for(j=ncl;j<nch;j++){
				if(I[i][j]<=40)
					I[i][j]=255;
				else
					I[i][j]=0;
		}
    }
	
	
	I_temp=bmatrix(nrl,nrh,ncl,nch);
	//memcpy(I_temp,I,nrh*nch);
		//Definition de nrl, nrh, ncl, nch dans LoadPGM_bmatrix
		//*nrl = 0;
		//*nrh = height - 1;
		//*ncl = 0;
		//*nch = width - 1;
	for(i=nrl+1;i<nrh-1;i++){
		for(j=ncl+1;j<nch-1;j++){
				//printf("%d:%d ",i,j);
				//I[i][j] = filter_moyenne(I, i, j);
				
				//sobel basique
				//I_temp[i][j] = filter_sobel(I, i, j);
				
				//sobel vertical
				//I_temp[i[j] = filter_sobelVertical(I, i, j);
				
				//norme de sobel (Ix + Iy)^2
				I_temp[i][j] = sqrt(filter_sobelVertical(I, i, j)^2 + filter_sobel(I, i, j)^2);
				
			}
		printf("\n");
	}
	
	
	sprintf(filename,"%s%d.pgm",filename,(int)(rand()%100));
	SavePGM_bmatrix(I_temp,nrl,nrh,ncl,nch,filename);
	sprintf(filename,"%s%d_original.pgm",filename,(int)(rand()%100));
	SavePGM_bmatrix(I,nrl,nrh,ncl,nch,filename);
	free_i16matrix(I,nrl,nrh,ncl,nch);
	free_i16matrix(I_temp,nrl,nrh,ncl,nch);


	return 1;

}

